package com.fc.app.fcapp.db;

import android.content.Context;
import android.database.Cursor;
import android.text.TextUtils;
import android.util.Log;

import com.fc.app.fcapp.FCApplication;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2018/2/24.
 */


public class AdDbManagerImpl implements IAdDbManager {
    private final String tableName = "ad_msg_data_table";
    private String dbPath = "AD";
    private final String dbName = "ad_msg";
    private Context mContext;
    private DBUtil skyDBUtil;

    private final String[][] baseDataColumnsAndTypes = {{"id", "INTEGER PRIMARY KEY AUTOINCREMENT"},
            {"adID", DBUtil.FILED_TYPE_STRING}, {"md5", DBUtil.FILED_TYPE_STRING},
            {"resUri", DBUtil.FILED_TYPE_STRING}, {"nativeUri", "TEXT UNIQUE"},
            {"attrDuration", DBUtil.FILED_TYPE_INT},
            {"attrOnclick", DBUtil.FILED_TYPE_STRING}
    };

    public static synchronized AdDbManagerImpl getInstance() {

        if (singleHolder.instance == null) {
            singleHolder.instance = new AdDbManagerImpl();
            singleHolder.instance.init();
        }
        return singleHolder.instance;
    }

    private static class singleHolder {
        public static AdDbManagerImpl instance = null;
    }

    private AdDbManagerImpl() {
    }

    /**
     * 创建数据库路径及文件
     */
    private synchronized void init() {
        mContext = FCApplication.getContext();
        skyDBUtil = new DBUtil(getFilePathDBName(mContext));
        skyDBUtil.createTable(tableName, baseDataColumnsAndTypes);

    }

    private String getFilePathDBName(Context context) {
        dbPath = context.getFilesDir().getAbsolutePath() + File.separator + dbPath + File.separator;
        if (!(new File(dbPath).exists())) {
            new File(dbPath).mkdir();
        }
        return dbPath + dbName;
    }


    @Override
    public boolean insert(AdMsgData data) {
        if (data == null) {
            return false;
        }
        Object[] baseDataObj = new Object[]{
                null,
                data.getAdID(),
                data.getMd5(),
                data.getResUri(),
                data.getNativeUri(),
                data.getAttrDuration(),
                data.getAttrOnclick()

        };

        try {
            createDBFileIfNotExist();
            createDBTableIfNotExist();
            skyDBUtil.insert(tableName, baseDataObj);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }

        return true;
    }

    @Override
    public void deleteById(Long id) {
        if (id == null) {
            return;
        }

        String sql = "delete from " + tableName + " where id = " + id;
        try {
            createDBFileIfNotExist();
            createDBTableIfNotExist();
            skyDBUtil.exec(sql);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public AdMsgData queryByResUri(String resUri) {
        if (TextUtils.isEmpty(resUri)) {
            return null;
        }
        String sql = "select * from " + tableName + " where resUri = " + "'" + resUri + "'";
        List<AdMsgData> dataList = null;
        try {
            createDBFileIfNotExist();
            createDBTableIfNotExist();

            dataList = (List<AdMsgData>) skyDBUtil.query(sql, null, new DBUtil.QueryHandler() {
                @Override
                public Object onResult(Cursor cursor, Object obj) {
                    List<AdMsgData> list = new ArrayList<>();
                    boolean hasData = cursor.moveToFirst();
                    while (hasData) {
                        AdMsgData data = new AdMsgData();
                        data.setId(Long.valueOf(cursor.getLong(cursor.getColumnIndex("id"))));
                        data.setAdID(String.valueOf(cursor.getString(cursor.getColumnIndex("adID"))));
                        data.setMd5(String.valueOf(cursor.getString(cursor.getColumnIndex("md5"))));
                        data.setResUri(String.valueOf(cursor.getString(cursor.getColumnIndex("resUri"))));
                        data.setNativeUri(String.valueOf(cursor.getString(cursor.getColumnIndex("nativeUri"))));
                        data.setAttrDuration(Integer.valueOf(cursor.getString(cursor.getColumnIndex("attrDuration"))));
                        data.setAttrOnclick(String.valueOf(cursor.getString(cursor.getColumnIndex("attrOnclick"))));
                        list.add(data);
                        hasData = cursor.moveToNext();
                    }
                    return list;
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (dataList == null || dataList.size() == 0) {
            return null;
        } else {
            return dataList.get(0);
        }
    }

    @Override
    public List<AdMsgData> queryAll() {
        String sql = "select * from " + tableName + " order by id desc";
        List<AdMsgData> dataList = null;
        try {
            createDBFileIfNotExist();
            createDBTableIfNotExist();
            Log.i("xxx","queryAll()11111111111" );
            dataList = (List<AdMsgData>) skyDBUtil.query(sql, null, new DBUtil.QueryHandler() {
                @Override
                public Object onResult(Cursor cursor, Object obj) {
                    List<AdMsgData> list = new ArrayList<>();
                    boolean hasData = cursor.moveToFirst();
                    while (hasData) {
                        AdMsgData data = new AdMsgData();
                        data.setId(Long.valueOf(cursor.getLong(cursor.getColumnIndex("id"))));
                        data.setAdID(String.valueOf(cursor.getString(cursor.getColumnIndex("adID"))));
                        data.setMd5(String.valueOf(cursor.getString(cursor.getColumnIndex("md5"))));
                        data.setResUri(String.valueOf(cursor.getString(cursor.getColumnIndex("resUri"))));
                        data.setNativeUri(String.valueOf(cursor.getString(cursor.getColumnIndex("nativeUri"))));
                        data.setAttrDuration(Integer.valueOf(cursor.getString(cursor.getColumnIndex("attrDuration"))));
                        data.setAttrOnclick(String.valueOf(cursor.getString(cursor.getColumnIndex("attrOnclick"))));
                        list.add(data);
                        hasData = cursor.moveToNext();
                    }
                    Log.i("xxx","queryAll() " +list.size());
                    return list;
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
        Log.i("xxx","queryAll()22222222222" );
        return dataList;
    }

    @Override
    public void deleteAll() {
        try {
            createDBFileIfNotExist();
            createDBTableIfNotExist();
            skyDBUtil.deleteDb(tableName, null, null);
        } catch (Exception e) {
            e.printStackTrace();
        }

     String dbPPP = "ADDDD";
        dbPPP = mContext.getFilesDir().getAbsolutePath() + File.separator + dbPPP + File.separator;
            if (!(new File(dbPPP).exists())) {
                new File(dbPPP).mkdir();
            }
        Log.i("dbTest", "deleteAll: "+ dbPPP);
    }

    //files目录下的db文件
    private File getFile(Context context) {
        File file = new File("/data/data/" + context.getPackageName() + "/files/AD/" + dbName);
        return file;
    }

    private void createDBFileIfNotExist() {
        if (!getFile(mContext).exists()) {
            init();
        }
    }

    private void createDBTableIfNotExist() {
        if (!skyDBUtil.isTableExist(tableName)) {
            skyDBUtil.createTable(tableName, baseDataColumnsAndTypes);
        }
    }

    /**
     * 单元测试用
     */
    public void setContext(Context context) {
        mContext = context;
    }
}
